<template>

  <a-modal
    :mask-closable="false"
    :visible="detailsVisible2"
    title="事件历史详情"
    :class="['c-dialog-box',singlePage?'c-dialog-box-full':'']"
    :closable="!singlePage"
    :dialog-style="{height:'574px'}"
    :footer="null"
    :width="1200"
    :z-index="modalZIndexM"
    destroy-on-close
    centered
    @cancel="onClose"
  >
    <span slot="closeIcon" class="c-close-icon"><a-icon :component="require('@/assets/icon/close.svg')" /></span>
    <span v-if="!singlePage" class="new-page-btn" @click="goNewPageHandler(dotDetailuuid)"><a-icon :component="require('@/assets/icon/newPage.svg')" /></span>
    <!-- info -->
    <a-spin :spinning="getHistoryFlightCountDetailLoading" class="c-dialog-search-box">
      <a-row class="c-dialog-search-box-2">
        <a-col :span="2">
          <div class="fw-b fs-12 color-r">机号</div>
          <div class="fs-18 fw-b color-title numbers">{{ currentRow.tailNumber ||'--' }}</div>
        </a-col>
        <a-col :span="3">
          <div class="fw-b fs-12 color-r">事件代码</div>
          <div class="fs-18 fw-b color-title numbers">{{ currentRow.code||'--' }}</div>
        </a-col>
        <a-col :span="3">

          <div class="fw-b fs-12 color-r">故障类型</div>
          <div class="fs-18 fw-b color-title numbers">{{ currentRow.type||'--' }}</div>
        </a-col>
        <a-col :span="16">

          <div class="fw-b fs-12 color-r">故障名称</div>
          <div class="fs-18 fw-b color-title numbers text-over" :title="currentRow.description||'--'">{{ currentRow.description||'--' }}</div>
        </a-col>

      </a-row>
    </a-spin>
    <!-- search -->

    <!-- table -->

    <a-spin :spinning="getHistoryFlightCountDetailLoading" class="c-dialog-main-box beauty-scroll">
      <a-table
        class="fd2-table"
        size="middle"
        :columns="columns"
        :data-source="[...tableData]"
        :scroll="{y:vxeH}"
        :pagination="false"
        :loading="getHistoryFlightCountDetailLoading"
        :row-key="(row,index) =>index"
        :row-class-name="rowClassHandler"
      />

      <!-- <vxe-grid
        ref="xTable1"
        class="event-trigger-packet-upload"
        show-overflow
        stripe
        highlight-hover-row
        :columns="columns"
        :data="tableData"
        :height="vxeH"
        :sort-config="{trigger: 'cell'}"
      /> -->
    </a-spin>
  </a-modal>
</template>

<script>
import { mapState, mapActions, mapMutations } from 'vuex';
import { downloadUrl } from '@/utils/util';
import rowClass from '@/pages/common/rowClass';
import { activeList } from '@/pages/common/constant.js';
export default {
  mixins: [rowClass],
  props: {

    reportHandler: {
      type: Function,
      default() {
        return function() {};
      }
    }

  },
  data() {
    return {
      currentRow: {},
      modalZIndexM: 2000,
      vxeH: '395px',
      legsArr: [1, 10, 20, 50, 100],
      timeRange: ['本周', '本月', '最近三个月', '最近六个月', '最近一年'],
      timeSelected: undefined,
      search: {},
      eventType: ''
    };
  },
  computed: {
    ...mapState('faultMonitoring', [
      'getHistoryFlightCountDetailLoading',
      'historyFlightCountDetail',
      'detailsVisible2'
    ]),
    ...mapState('fraMonitoring', [
      'modalZIndex'
    ]),
    tableData() {
      return this.currentRow?.details ?? [];
    },

    singlePage() {
      return ((this.$route.meta?.singlePage ?? false) && this.$route.query.rp === 'detailsVisible2');
    },
    columns() {
      if (['FDE', 'MMO', 'SMT', 'EF-FDE', 'EF-MMO', 'EF-SMT'].includes(this.eventType) || /(FDE|MMO|SMT)/.test(this.eventType)) {
        return [
          {
            title: '航段',
            align: 'left',
            dataIndex: 'leg',
            width: 120,
            customRender: (value, row) => {
              return [
                <span>{this.$legHandler(row.leg, row.totalLeg)}</span>,
                [<a class='ml-16' onClick={(e) => this.reportHandler({ ...row, latestAcarsTime: row.legDate, id: row.legId, ...this.currentRow, tailnumber: this.currentRow?.tailNumber ?? '' }, 'faultReportVisible')}>PLF</a>]
              ];
            }
          },
          {
            title: '航班号',
            align: 'left',
            width: 75,
            dataIndex: 'flightNo',
            customRender: (value, row) => {
              return row.flightNo ? [<a onClick={(e) => this.reportHandler({ ...row, ...this.currentRow, tailnumber: this.currentRow?.tailNumber ?? '', id: row.legId }, 'flightLegDetailsVisible')}>{row.flightNo}</a>] : '--';
            }

          },

          {
            title: '航段时间',
            align: 'left',
            width: 160,
            dataIndex: 'legDate',
            customRender: (value, row) => {
              const legDate = row.legDate;
              return [
                <div>
                  {legDate ? this.$moment.utc(legDate).format('YYYY-MM-DD HH:mm:ss') : '--'}
                </div>
              ];
            }

          },
          {
            title: '起飞机场',
            align: 'left',
            dataIndex: 'dep',
            width: 75,
            customRender: (value, row) => {
              return row.dep ? [<a onClick={() => this.airportInfoHandler(row.dep)}>{row.dep }</a>] : '--';
            }

          },
          {
            title: '落地机场',
            align: 'left',
            dataIndex: 'arr',
            width: 75,
            customRender: (value, row) => {
              return row.arr ? [<a onClick={() => this.airportInfoHandler(row.arr)}>{row.arr }</a>] : '--';
            }
          },
          {
            title: '消息时间',
            dataIndex: 'msgTime',
            align: 'left',
            width: 160,
            customRender: (value, row) => {
              const time = row.msgTime;

              return time ? this.$moment.utc(time).format('YYYY-MM-DD HH:mm:ss') : '--';
            }

          },
          {
            title: '关联MMSG',
            align: 'left',
            dataIndex: 'eventDetails',
            customRender: (value, row) => {
              const ca = [];
              row.eventDetails?.forEach(item => {
                ca.push(<div>{item.code ? <a onClick={() => this.clickCodeHandler(item)}>{item.code}</a> : '--'}</div>);
              });
              return ca.length > 0 ? ca : '--';
            }

          },

          {
            title: '飞行阶段',
            dataIndex: 'phase',
            align: 'left',
            width: 110,
            customRender: (value, row) => {
              const ca = [];
              row.eventDetails?.forEach(item => {
                ca.push(<div>{item.phase ?? '--'}</div>);
              });
              return ca.length > 0 ? ca : '--';
            }

          },
          {
            title: 'MMSG Activity',
            dataIndex: 'Activity',
            align: 'left',
            customRender: (value, row) => {
              const ca = [];
              row.eventDetails?.forEach(item => {
                ca.push(<div>{activeList.find(acItem => acItem.value === item.activity)?.name ?? '--'}</div>);
              });
              return ca.length > 0 ? ca : '--';
            }
          }
          // {
          //   title: 'Intermittence',
          //   dataIndex: 'Intermittence',
          //   align: 'left',
          //   customRender: (value, row) => {
          //     const ca = [];
          //     row.eventDetails?.forEach(item => {
          //       ca.push(<div>{(item.intermittence ?? '--') + (item.intermittenceNum ? `(${item.intermittenceNum})` : '')}</div>);
          //     });
          //     return ca.length > 0 ? ca : '--';
          //   }

          // }
        ];
      } else if (/MMSG|MSG/.test(this.eventType)) {
        return [
          {
            title: '航段',
            align: 'left',
            dataIndex: 'leg',
            width: 120,
            customRender: (value, row) => {
              return [
                <span>{this.$legHandler(row.leg, row.totalLeg)}</span>,
                [<a class='ml-16' onClick={(e) => this.reportHandler({ ...row, latestAcarsTime: row.legDate, id: row.legId, ...this.currentRow, tailnumber: this.currentRow?.tailNumber ?? '' }, 'faultReportVisible')}>PLF</a>]
              ];
            }
          },
          {
            title: '航班号',
            align: 'left',
            width: 75,
            dataIndex: 'flightNo',
            customRender: (value, row) => {
              return row.flightNo ? [<a onClick={(e) => this.reportHandler({ ...row, ...this.currentRow, tailnumber: this.currentRow?.tailNumber ?? '', id: row.legId }, 'flightLegDetailsVisible')}>{row.flightNo}</a>] : '--';
            }

          },

          {
            title: '航段时间',
            align: 'left',
            width: 160,
            dataIndex: 'legDate',
            customRender: (value, row) => {
              const legDate = row.legDate;
              return [
                <div>
                  {legDate ? this.$moment.utc(legDate).format('YYYY-MM-DD HH:mm:ss') : '--'}
                </div>
              ];
            }
          },
          {
            title: '起飞机场',
            align: 'left',
            dataIndex: 'dep',
            width: 75,
            customRender: (value, row) => {
              return row.dep ? [<a onClick={() => this.airportInfoHandler(row.dep)}>{row.dep }</a>] : '--';
            }
          },
          {
            title: '落地机场',
            align: 'left',
            dataIndex: 'arr',
            width: 75,
            customRender: (value, row) => {
              return row.arr ? [<a onClick={() => this.airportInfoHandler(row.arr)}>{row.arr }</a>] : '--';
            }
          },
          {
            title: '消息时间',
            dataIndex: 'msgTime',
            align: 'left',
            width: 160,
            customRender: (value, row) => {
              const msgTime = row.msgTime;
              return [
                <div>
                  {msgTime ? this.$moment.utc(msgTime).format('YYYY-MM-DD HH:mm:ss') : '--'}
                </div>
              ];
            }
          },
          {
            title: '关联Fault代码',
            align: 'left',
            width: 140,
            dataIndex: 'eventDetails',
            customRender: (value, row) => {
              const ca = [];
              row.eventDetails?.forEach(item => {
                ca.push(<div >{item.code ? <a onClick={() => this.clickCodeHandler(item)}>{item.code}</a> : '--'}</div>);
              });
              return ca.length > 0 ? ca : '--';
            }

          },

          {
            title: '飞行阶段',
            dataIndex: 'phase',
            align: 'left',
            width: 110,
            customRender: (value, row) => {
              const ca = [];
              row.eventDetails?.forEach(item => {
                ca.push(<div>{item.phase ?? '--'}</div>);
              });
              return ca.length > 0 ? ca : '--';
            }

          },
          {
            title: 'Activity',
            dataIndex: 'Activity',
            align: 'left',
            width: 90,
            customRender: (value, row) => {
              const ca = [];
              row.eventDetails?.forEach(item => {
                ca.push(<div>{activeList.find(acItem => acItem.value === item.activity)?.name ?? '--'}</div>);
              });
              return ca.length > 0 ? ca : '--';
            }
          }
          // {
          //   title: 'Intermittence',
          //   dataIndex: 'Intermittence',
          //   align: 'left',
          //   customRender: (value, row) => {
          //     const ca = [];
          //     row.eventDetails?.forEach(item => {
          //       ca.push(<div>{(item.intermittence ?? '--') + (item.intermittenceNum ? `(${item.intermittenceNum})` : '')}</div>);
          //     });
          //     return ca.length > 0 ? ca : '--';
          //   }

          // }
        ];
      } else {
        return [
          {
            title: '航段',
            align: 'left',
            dataIndex: 'leg',
            customRender: (value, row) => {
              return [
                <span>{this.$legHandler(row.leg, row.totalLeg)}</span>,
                [<a class='ml-16' onClick={(e) => this.reportHandler({ ...row, latestAcarsTime: row.legDate, id: row.legId, ...this.currentRow, tailnumber: this.currentRow?.tailNumber ?? '' }, 'faultReportVisible')}>PLF</a>]
              ];
            }
          },

          {
            title: '航班号',
            align: 'left',
            dataIndex: 'flightNo',
            customRender: (value, row) => {
              return row.flightNo ? [<a onClick={(e) => this.reportHandler({ ...row, ...this.currentRow, tailnumber: this.currentRow?.tailNumber ?? '', id: row.legId }, 'flightLegDetailsVisible')}>{row.flightNo}</a>] : '--';
            }

          },

          {
            title: '航段时间',
            align: 'left',
            dataIndex: 'legDate',
            customRender: (value, row) => {
              const legDate = row.legDate;
              return [
                <div>
                  {legDate ? this.$moment.utc(legDate).format('YYYY-MM-DD HH:mm:ss') : '--'}
                </div>
              ];
            }
          },
          {
            title: '起飞机场',
            align: 'left',
            dataIndex: 'dep',
            width: 80,

            customRender: (value, row) => {
              return row.dep ? [<a onClick={() => this.airportInfoHandler(row.dep)}>{row.dep }</a>] : '--';
            }

          },
          {
            title: '落地机场',
            align: 'left',
            dataIndex: 'arr',
            width: 80,
            customRender: (value, row) => {
              return row.arr ? [<a onClick={() => this.airportInfoHandler(row.arr)}>{row.arr }</a>] : '--';
            }
          },
          {
            title: '消息时间',
            dataIndex: 'msgTime',
            align: 'left',
            customRender: (value, row) => {
              const msgTime = row.msgTime;
              return [
                <div>
                  {msgTime ? this.$moment.utc(msgTime).format('YYYY-MM-DD HH:mm:ss') : '--'}
                </div>
              ];
            }
          }

        ];
      }
    }

  },
  watch: {
    'detailsVisible2': {
      handler(nv) {
        if (nv) {
          this.setState({ key: 'modalZIndex', payload: this.modalZIndex + 1 });
          this.modalZIndexM = this.modalZIndex;
          this.dotDetailuuid = this.$route?.query?.dotDetailuuid ?? new Date().getTime();
          this.changeVisiable();
        }
      },
      immediate: true
    }

  },
  methods: {

    ...mapActions('faultMonitoring', [
      'getHistoryFlightCountDetail'
    ]),
    ...mapMutations('fraMonitoring', [
      'setState'
    ]),
    ...mapMutations('faultMonitoring', {
      'setFState': 'setState'
    }),
    ...mapActions('eventMonitoring', [
      'downLoadFile'
    ]),
    async changeVisiable() {
      const params = sessionStorage.getItem(`ddu${this.dotDetailuuid}`) ?? localStorage.getItem('dotDetailRow') ?? {};
      const parasmF = JSON.parse(params);
      this.eventType = parasmF.type;
      await this.getHistoryFlightCountDetail(parasmF);

      this.currentRow = this.historyFlightCountDetail;
      this.vxeH = this.singlePage ? `${document.body.clientHeight - 180 - 50}px` : '345px';
    },
    // 当drawer点击关闭
    onClose() {
      this.setFState({ key: 'detailsVisible2', payload: false });
    },

    selectTimeHandler(t) {
      switch (t) {
        case '本周':
          this.search.timeRange = 7;
          break;
        case '本月':
          this.search.timeRange = this.$moment.utc().daysInMonth();
          break;
        case '最近三个月':
          this.search.timeRange = this.$moment.utc().diff(this.$moment.utc().add(-3, 'M'), 'day');
          break;
        case '最近六个月':
          this.search.timeRange = this.$moment.utc().diff(this.$moment.utc().add(-6, 'M'), 'day');
          break;
        case '最近一年':
          this.search.timeRange = this.$moment.utc().diff(this.$moment.utc().add(-1, 'y'), 'day');
          break;
      }
    },
    airportInfoHandler(code) {
      this.setState({ key: 'airportInfoVisible', payload: true });
      localStorage.setItem('apInfoCode', code);
    },
    downloadHandler(fileName) {
      this.downLoadFile({ fileName }).then(res => {
        const FileName = decodeURI(
          res.headers['content-disposition'].split(';')[1].split('=')[1]
        );
        const type = decodeURI(
          res.headers['content-type']
        );
        downloadUrl(res.data, FileName, type);
      });
    },
    clickCodeHandler(row) {
      const params = sessionStorage.getItem(`ddu${this.dotDetailuuid}`) ?? localStorage.getItem('dotDetailRow') ?? {};
      const parasmF = JSON.parse(params);
      const newType = row.msgType === 'Alert' ? row.msgType : row.name;
      const newParams = { ...parasmF, type: newType, code: row.code };
      localStorage.setItem('dotDetailRow', JSON.stringify(newParams));
      if (this.singlePage) {
        sessionStorage.setItem(`ddu${this.dotDetailuuid}`, localStorage.getItem('dotDetailRow'));
      }
      this.changeVisiable();
    },
    goNewPageHandler(dotDetailuuid = '') {
      sessionStorage.setItem(`ddu${dotDetailuuid}`, localStorage.getItem('dotDetailRow'));
      const routeData = this.$router.resolve({
        path: '/reportsLayout',
        query: {
          rp: 'detailsVisible2',
          dotDetailuuid
        }
      });

      window.open(routeData.href, '_blank');
    }
  }
};
</script>

<style lang="less">
@import './index.less';
</style>
